package hhtc.jsjds.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hhtc.jsjds.entity.CategoryPojo;
import hhtc.jsjds.entity.FinalSeqPojo;
import hhtc.jsjds.enums.StatusCodeEnum;
import hhtc.jsjds.exception.XscoderException;
import hhtc.jsjds.service.AreaService;
import hhtc.jsjds.service.CategoryService;
import hhtc.jsjds.service.FinalSeqService;
import hhtc.jsjds.vo.AreaGroupVO;
import hhtc.jsjds.vo.FinalSeqExcelVO;
import hhtc.jsjds.vo.FinalTeamSeqVO;
import hhtc.jsjds.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 最终答辩顺序(FinalSeq)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("finalSeq")
public class FinalSeqController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private FinalSeqService finalSeqService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @return 所有数据
     */
    @GetMapping
    public Result selectAll(Page<FinalTeamSeqVO> page, Map<String, Object> search) {
        Page<FinalTeamSeqVO> result = finalSeqService.getAll(page, search);
        return new Result(true, StatusCodeEnum.OK, result);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.finalSeqService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param finalSeqPojo 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody FinalSeqPojo finalSeqPojo) {
        return success(this.finalSeqService.save(finalSeqPojo));
    }

    /**
     * 修改数据
     *
     * @param finalSeqPojo 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody FinalSeqPojo finalSeqPojo) {
        return success(this.finalSeqService.updateById(finalSeqPojo));
    }

    /**
     * 删除数据
     *
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete() {
        this.finalSeqService.removeAll();
        return new Result(true, StatusCodeEnum.OK);
    }

    /**
     * 将进入答辩的队伍进行分组抽签
     *
     * @return
     */
    @GetMapping("/group")
    public Result group() {

        int count = finalSeqService.count();
        if (count != 0) {
            throw new XscoderException(StatusCodeEnum.GROUP_IS_EXIT);
        }
        int categoryCount = categoryService.count(new QueryWrapper<CategoryPojo>().eq("parent_id", 0));
        int areaCount = areaService.count();
        if (categoryCount != areaCount) {
            throw new XscoderException(StatusCodeEnum.AREA_NOT_COMPLETE);
        }
        try {
            finalSeqService.group();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCodeEnum.GROUP_FAIL);
        }
        return new Result(true, StatusCodeEnum.OK);
    }


    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        OutputStream os = null;// 取得输出流
        ExcelWriter excelWriter = null;
        try {
            os = response.getOutputStream();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            //响应内容格式
            response.setContentType("application/vnd.ms-excel");
            String fileName = "答辩顺序" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("content-Disposition", "attachment;fileName=" + fileName);// 设定输出文件头，这里fileName=后面跟的就是文件的名称，可以随意更改
            List<AreaGroupVO> areaGroupVOS = areaService.getGroupConcatIdAndCategoryId();
            int idx = 0;
            excelWriter = EasyExcel.write(os, FinalSeqExcelVO.class).build();
            for (AreaGroupVO areaGroupVO : areaGroupVOS) {
                String[] ids = areaGroupVO.getGroupId().split(",");
                List<String> idList = Arrays.asList(ids);
                List<FinalSeqExcelVO> data = finalSeqService.getExportExcelMsg(idList);
                if (CollectionUtils.isNotEmpty(data)) {
                    WriteSheet writeSheet = EasyExcel.writerSheet(idx, "答辩场" + idx + "-" + areaGroupVO.getAreaName()).build();
                    excelWriter.write(data, writeSheet);
                    idx++;
                }
            }
        } catch (Exception e) {
            log.info("/finalSeq/exportExcel异常：{}", e);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
